package org.redmagic.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Properties;

public final class Properties2 {

    public static void loadProperties(URI uri, Properties propertyContainer) {
        loadProperties(uri.toASCIIString(), propertyContainer);
    }

    public static void loadProperties(String fileName, Properties propertyContainer) {
        Properties properties = load(fileName);
        propertyContainer.putAll(properties);
    }

    public static Properties load(URI uri) {
        return load(uri.toASCIIString());
    }

    public static Properties load(String fileName) {
        return load(new File(fileName));
    }

    public static Properties load(File file) {
        try {
            return load(new FileInputStream(file), file.getAbsolutePath().endsWith(".xml"));
        } catch (FileNotFoundException fnfe) {
            throw new RuntimeException(fnfe.getMessage(), fnfe);
        }
    }

    public static Properties load(InputStream inputStream, boolean isXml) {
        Properties properties = new Properties();
        try {
            if (isXml) {
                properties.loadFromXML(inputStream);
            } else {
                properties.load(inputStream);
            }
        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        } finally {
            Closeables.closeQuietly(inputStream);
        }
        return properties;
    }

    public static void storeProperties(Properties properties, URI uri) {
        OutputStream os = null;

        try {
            os = new FileOutputStream(new File(uri));
            properties.store(os, "RedMagic - Last known good configuration");
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            Closeables.closeQuietly(os);
        }

    }
}